package com.LeeCode;

import java.util.HashMap;
import java.util.Map;

/**
 * 回旋镖的数量
 */

public class Code447 {
    public static void main(String[] args) {
        int[][] points = {{0, 0}, {1, 0}, {-1, 0}, {0, 1}, {0, -1}};
        System.out.println(new Code447().numberOfBoomerangs(points));
    }

    public int numberOfBoomerangs(int[][] points) {
        int result = 0;
        int n = points.length;
        // 存储距离平方和对应的点的个数
        Map<Integer, Integer> distanceCount = new HashMap<>();

        // 对每个点作为中心点
        for (int i = 0; i < n; i++) {
            distanceCount.clear();

            // 计算当前点到其他所有点的距离
            for (int j = 0; j < n; j++) {
                if (i != j) {
                    int distance = getDistanceSquared(points[i], points[j]);
                    distanceCount.merge(distance, 1, Integer::sum);
                }
            }

            // 对于每个距离，如果有m个点，可以组成m*(m-1)个回旋镖
            for (int count : distanceCount.values()) {
                if (count > 1) {
                    result += count * (count - 1);
                }
            }
        }

        return result;
    }

    // 计算两点间距离的平方（避免浮点运算）
    private int getDistanceSquared(int[] point1, int[] point2) {
        int dx = point1[0] - point2[0];
        int dy = point1[1] - point2[1];
        return dx * dx + dy * dy;
    }
}
